package top.anydata.lifeofcode.lifesystem.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.Map;

/**
 * 功能描述:加解密处理
 *
 * @author <a href="mailto:caingao@anydata.top">CainGao</a>
 * @version V_1.0
 * @date 2024/5/9 1:49 PM
 */
public class EncryptUtils {

    private static final String RSA_ALGORITHM = "RSA";

    private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding"; // 指定加密算法、模式和填充方式

    private static final String AES_IV = "1234567890123456"; // 16字节的IV

    public static String rsaEncrypt(String data, String publicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        byte[] encryptedData = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    public static String rsaDecrypt(String data, String privateKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
        PrivateKey privKey = keyFactory.generatePrivate(keySpec);

        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privKey);

        return new String(cipher.doFinal(Base64.getDecoder().decode(data)));
    }

    /**
     * 功能描述
     *
     * @author: <a href="mailto:caingao@anydata.top">CainGao</a>
     * @date: 2:00 PM 2024/5/9
     * @param: []
     * @return: void
     */
    public static Map<String, String> generateKeyPair() throws NoSuchAlgorithmException {
        Map<String, String> keyPairMap = new java.util.HashMap<>();
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();
        keyPairMap.put("publicKey", Base64.getEncoder().encodeToString(publicKey.getEncoded()));
        keyPairMap.put("privateKey", Base64.getEncoder().encodeToString(privateKey.getEncoded()));
        return keyPairMap;
    }

    public static String generateAESKeyAsString(int keySize) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(keySize, new SecureRandom()); // keySize通常是128, 192或256位
        SecretKey secretKey = keyGenerator.generateKey();
        // 获取密钥的字节数组表示
        byte[] keyBytes = secretKey.getEncoded();
        // 使用Base64编码将字节数组转换为字符串
        return Base64.getEncoder().encodeToString(keyBytes);
    }

    /**
     * 功能描述: AES加密
     *
     * @author: <a href="mailto:caingao@anydata.top">CainGao</a>
     * @date: 2:29 PM 2024/5/9
     * @param: [key, data]
     * @return: byte[]
     */
    public static byte[] aesEncrypt(String aesKey,String data) throws Exception {
        // Base64解码密钥
        byte[] keyBytes = Base64.getDecoder().decode(aesKey);
        byte[] iv = AES_IV.getBytes(); // 16字节的IV
        // 创建SecretKeySpec
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        // 实例化Cipher对象并初始化为加密模式
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        // 加密数据并返回
        return cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 功能描述: AES解密
     *
     * @author: <a href="mailto:caingao@anydata.top">CainGao</a>
     * @date: 2:29 PM 2024/5/9
     * @param: [key, encryptedData]
     * @return: byte[]
     */
    public static byte[] aesDecrypt(SecretKey key, byte[] encryptedData) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(encryptedData);
    }


    public static void main(String[] args) throws Exception {
        String code = Base64.getEncoder().encodeToString(aesEncrypt("LW/g7jYs0gkat3M2P2JV+g==","123"));
        System.out.println(code);
    }

}
